<?php

namespace control;
//管理员后台-线边库存
class tempInventoryClass extends adIndexClass
{
    private const title = '线边库存';
    private const page  = 'tempInventory';
    private const table = 'line_inventory';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'line'    => [
                        'name'  => "生产线",
                        'width' => 300,
                    ],
                    'subject' => [
                        'name'  => '存货类别',
                        'width' => 200,
                    ],
                    'code'    => [
                        'name'  => '物料编码',
                        'width' => 200,
                        'sort'  => 1,
                    ],
                    'name'    => [
                        'name'  => '物料名称',
                        'width' => 200,
                    ],
                    'model'   => [
                        'name'  => '规格型号',
                        'width' => 200,
                    ],
                    'unit'    => [
                        'name'  => '单位',
                        'width' => 200,
                    ],
                    'num'     => [
                        'name'  => '当前库存数量',
                        'width' => 200,
                        'sort'  => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        $materialClass = new materialClass();
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "生产线"  => selectMultiple(["name" => "lineId", 'table' => "product_line", 'field' => "concat(workshop,'-',name) as name,id", 'sqlId' => 'id', 'where' => "coid = '" . self::$coid . "' order by time", 'sqlField' => 'name', 'class' => 'width200']),
                    "物料编码" => text(array("name" => "code")),
                    "物料名称" => text(array("name" => "materialName")),
                ],
                [
                    "规格型号" => text(array("name" => "model")),
                    '存货类别' => select(array('name' => 'materialType', 'title' => '存货类别', 'option' => $materialClass->checkOption)),
                ]
            ]
        ], 1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 查询条件
     *
     * @return string
     */
    public function home(): string
    {
        $showZero = static::rGet(self::$stid . self::page . 'ShowZero');
        $html     = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .= "<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'" . self::page . "'})\">导出</span>";
        }
        $button .= "&emsp;" . checkbox(array('name' => 'showZero', 'value' => ['show' => '展示数量为0的库存'], 'checked' => [$showZero]));
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*列表页-查询结果*/
    public function homeSearch(): string
    {
        $showZero = static::rGet(self::$stid . self::page . 'ShowZero');
        //查询结果
        $where     = search([
            "like" => [
                'b.code'  => $this->post('code'),
                'b.name'  => $this->post('materialName'),
                'b.model' => $this->post('model'),
            ],
            "="    => [
                'a.coid'    => self::$coid,
                'b.subject' => $this->post('materialType'),
                'lineId'    => $this->post('lineId')
            ],
        ]);
        $condition = !$showZero ? 'having sum(any_value(num)) >0' : '';
        //排序
        $orderBy                     = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'code',
            "sort"   => $this->post('list_sort') ?: "desc",
            "array"  => array(),
        ));
        $page                        = $this->page([
            "table" => "(select lineId,materialId,b.code,b.name,b.model,b.unit,b.subject,a.num from line_inventory as a join material as b on a.materialId = b.id where 1=1 $where order by a.time desc) as cc",
            'field' => "materialId,lineId,any_value(code) as code,any_value(name) as name,any_value(model) as model,any_value(unit) as unit,any_value(subject) as subject,ifnull(sum(any_value(num)),0) as num",
            "where" => ' 1=1  group by lineId,materialId ' . $condition,
            "order" => $orderBy['orderBy']
        ]);
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'line':
                        $line  = query('product_line', " id = '$array[lineId]'");
                        $row[] = $line['workshop'] . $line['name'];
                        break;
                    case 'num':
                        $row[] = self::lostZero($array['num'], 'numPrecision');
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $totalQuery = mysqli_fetch_assoc(sqlExec(" select ifnull(sum(num),0) as num from (select lineId,materialId,b.code,b.name,b.model,b.unit,b.subject,a.num from line_inventory as a join material as b on a.materialId = b.id where 1=1 {$where} order by a.time desc) as cc ", true));
        $total    = [
            'num'        => self::lostZero($totalQuery['num'], 'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $this->js() . $page['button'];
        return json_encode($json, 320);
    }

    public function js()
    {
        return <<<eof
<script>
$("[name='showZero[]'][type='checkbox']").on('click',function() {
    let show = '';
    if ($(this).is(":checked")){
       show = 'show';
    }
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=showZero',{show:show},function(res) {
         if (res.warn === 2){
             searchFormSub('tempInventory','homeSearch')
         }
    },'json')
}) 
</script>
eof;

    }

    public function showZero(): bool|string
    {
        $json['warn'] = 2;
        static::rSet(self::$stid . self::page . 'ShowZero', $this->post('show'));
        return json_encode($json, 320);
    }

    /**
     * 线边库存
     * @param $materialId
     * @param $unit
     * @param string $lineId
     * @return float|int
     */
    public static function inventoryNum($materialId, $unit, $lineId = ''): float|int
    {
        if (empty($materialId) || empty($unit)) {
            return 0;
        }
        $where = '';
        if ($lineId) {
            $where .= " and lineId = '$lineId'";
        }
        $material = query('material', "id = '$materialId'");
        $num      = find(array('table' => 'line_inventory', 'where' => "coid = '" . self::$coid . "' and materialId = '$materialId'" . $where, 'sum' => "num"));
        return machiningOrderClass::material_num_change($materialId, $material['unit'], $unit, $num);
    }

    /**
     * 生成线边库存记录
     * @param $array
     * @return mixed
     */
    public static function insertRecord($array): mixed
    {
        $field      = array_merge($array, [
            'id'   => suiji(),
            'coid' => self::$coid,
        ]);
        $annotation = [
            'lineId'     => '生产线',
            'materialId' => '物料',
            'num'        => '数量',
        ];
        $rules      = [
            'lineId'     => 'required',
            'materialId' => 'required',
            'num'        => 'required|numeric',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            return $vt->getErrs()[0];
        } else {
            $warn = static::insert(array(
                'table' => self::table,
                'field' => $field
            ));
            if ($warn != '新增成功') {
                return '新增线边库存记录失败';
            }
        }
        return true;
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId     = $this->get('templateId');
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $data = [];
            /***********标题**********/
            $title        = [];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']) {
                    $title[] = $array['aliasName'];
                }
            }
            $sql    = $_SESSION[self::page]['sql'];
            $result = sqlFind($sql);
            //导出数据生成
            foreach ($result as $array) {
                $column = [];
                foreach ($tempFieldAll as $templateField) {
                    if ($templateField['display']) {
                        $column[] = match ($templateField['columnName']) {
                            '生产线' => productLineClass::getName($array['lineId']),
                            '存货类别' => $array['subject'],
                            '物料编码' => $array['code'],
                            '物料名称' => $array['name'],
                            '规格型号' => $array['model'],
                            '主单位' => $array['unit'],
                            '主单位数量' => self::lostZero($array['num'], 'numPrecision'),
                            default => '',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了" . self::title;
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, self::title . ".xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'生产线',
                    'aliasName'=>'生产线',
                ],
                [
                    'columnName'=>'存货类别',
                    'aliasName'=>'存货类别',
                ],
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'主单位',
                    'aliasName'=>'主单位',
                ],
                [
                    'columnName'=>'主单位数量',
                    'aliasName'=>'主单位数量',
                ],
            ]
        };
    }
}
